//
//  PersonalInfoViewController.m
//  项目三
//
//  Created by rimi1 on 2016/12/9.
//  Copyright © 2016年 Wangxingqian. All rights reserved.
//

#import "PersonalInfoViewController.h"
#import "PersonalChangePasswordViewController.h"

#import "PersonalInfoView.h"

#import "AVRequest+ChangeInfo.h"

@interface PersonalInfoViewController () <UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) PersonalInfoView *headView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <NSMutableDictionary *> *dataArr;
@property (nonatomic, strong) UIButton *signOut;

@end

@implementation PersonalInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeAppearance];
}

#pragma mark - initialize

- (void)initializeDataSource {
    self.dataArr = [NSMutableArray array];
    
    NSArray *titleArr = @[@"昵称", @"修改密码"];
    NSArray *contentArr = @[[MyUser sharedUser].name, @""];
    for (int i = 0; i < titleArr.count; i++) {
        NSMutableDictionary *dic = [@{@"title":titleArr[i], @"content":contentArr[i]} mutableCopy];
        [self.dataArr addObject:dic];
    }
}

- (void)initializeAppearance {
    self.navigationBar.title.text = @"个人信息";
    self.tableView.tableHeaderView = self.headView;
    self.tableView.tableFooterView = self.signOut;
    [self.view addSubview:self.tableView];
    [self assignment];
}

- (void)assignment {
    NSURL *url = [NSURL URLWithString:[MyUser sharedUser].headImage];
    [self.headView.headImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"个人"] options:SDWebImageProgressiveDownload];
    [self sexButtonStutasWithSex:[MyUser sharedUser].sex];
}

#pragma mark - URLRequest

- (void)urlHeadImageRequestWithImg:(UIImage *)img {
    NSData *data = UIImageJPEGRepresentation(img, 0.1);
    [AVRequest avHeadImageWithData:data headSueeccd:^(NSString *url, BOOL succeed, NSError *error) {
        if (error) {
            [Alert alertWithTitle:@"修改失败" message:nil];
            return;
        }
        
        if (succeed) {
            [Alert alertWithTitle:@"修改成功" message:nil];
            [MyUser sharedUser].headImage = url;
            self.headView.headImage.image = img;
        }else {
            [Alert alertWithTitle:@"修改失败" message:nil];
        }
    }];
}

- (void)urlNameRequestWithName:(NSString *)name {
    // 0 == 成功  1 == 失败 2 == 已存在昵称  3 == 有error
    [AVRequest avNameWithName:name block:^(NSInteger status, NSError *error) {
        if (error) {
            [Alert alertWithTitle:@"修改失败" message:nil];
            return;
        }
        
        if (status == 0) {
            [Alert alertWithTitle:@"修改成功" message:nil];
            [MyUser sharedUser].name = name;
            self.dataArr[0][@"content"] = name;
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        }else if (status == 1) {
            [Alert alertWithTitle:@"修改失败" message:nil];
        }else if (status == 2) {
            [Alert alertWithTitle:@"已存在昵称" message:nil];
        }
        
    }];
}

- (void)urlSexRequestWithSex:(NSString *)sex {
    [AVRequest avSexWithSex:sex sSueeccd:^(BOOL succeed, NSError *error) {
        if (error) {
            [Alert alertWithTitle:@"性别修改失败" message:nil];
            return;
        }
        if (succeed) {
            [MyUser sharedUser].sex = sex;
        }else {
            [Alert alertWithTitle:@"性别修改失败" message:nil];
        }
    }];
}

#pragma mark - Custom Method

- (void)sexButtonStutasWithSex:(NSString *)sex {
    if ([sex isEqualToString:@"男"]) {
        self.headView.boy.selected = YES;
        self.headView.girl.selected = NO;
        self.headView.boy.backgroundColor = [UIColor orangeColor];
        self.headView.girl.backgroundColor = [UIColor whiteColor];
    }else {
        self.headView.boy.selected = NO;
        self.headView.girl.selected = YES;
        self.headView.boy.backgroundColor = [UIColor whiteColor];
        self.headView.girl.backgroundColor = [UIColor orangeColor];
    }
}

#pragma mark - respondsTo...

- (void)respodnsToSignOut:(UIButton *)sender {
    [MyUser signOut];
    if (self.signOutBlock) {
        self.signOutBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}
// 点击头部
- (void)respondsToHead {
    [Alert alertWithPhoto:^{
        [self photoAlbum];
    } camera:^{
        [self takePhotos];
    }];
}

- (void)respondsToSex:(UIButton *)sender {
    if (sender.selected) {
        return;
    }
    
    [self sexButtonStutasWithSex:sender.titleLabel.text];
    [self urlSexRequestWithSex:sender.titleLabel.text];
}

#pragma mark - Camera
// 拍照
- (void)takePhotos {
    // 判断是否有前后摄像头(是否支持拍照)
    if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        [Alert alertWithTitle:@"不支持拍照功能" message:nil];
        return;
    }
    // 设置相机
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 推出相机
    [self presentViewController:imagePicker animated:YES completion:nil];
}
// 相册
- (void)photoAlbum {
    // 设置相册
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;
    // 进入编辑状态
    imagePicker.allowsEditing = YES;
    // 跳到系统相册
    [self presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
// 选中图片自动调用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    [self dismissViewControllerAnimated:YES completion:^{
        [self urlHeadImageRequestWithImg:image];
    }];
}
// 取消选择自动调用(右上角的Cancel)
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reusing = @"PersonalInfoCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusing];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reusing];
    }
    NSDictionary *dic = self.dataArr[indexPath.row];
    
    cell.textLabel.text = dic[@"title"];
    cell.detailTextLabel.text = dic[@"content"];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:{
            [Alert alertTextFieldWithTitle:@"修改昵称" message:nil sure:^(NSString *str) {
                if (str.length != 0) {
                    [self urlNameRequestWithName:str];
                }else {
                    [Alert alertWithTitle:@"昵称不能为空" message:nil];
                }
            }];
        }
            break;
            
        case 1:{
            PersonalChangePasswordViewController *pass = [[PersonalChangePasswordViewController alloc] init];
            [self.navigationController pushViewController:pass animated:YES];
        }
            break;
            
        default:
            break;
    }
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

#pragma mark - get

- (PersonalInfoView *)headView {
    
    if (!_headView) {
        
        _headView = [[PersonalInfoView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, WXQAdaptionHeight(140) + 55 + WXQAdaptionHeight(10))];
        
        __weak PersonalInfoViewController *info = self;
        _headView.tapButton = ^(UIButton *sender) {
            [info respondsToSex:sender];
        };
        _headView.tapHead = ^() {
            [info respondsToHead];
        };
        
    }
    return _headView;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kWIDTH, kHEIGHT - 64) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        
    }
    return _tableView;
}

- (UIButton *)signOut {
    
    if (!_signOut) {
        
        _signOut = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 44)];
        _signOut.layer.cornerRadius = 5;
        _signOut.backgroundColor = [UIColor orangeColor];
        [_signOut setTitle:@"退出登录" forState:UIControlStateNormal];
        [_signOut setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_signOut addTarget:self action:@selector(respodnsToSignOut:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _signOut;
}


@end











